import { useEffect, useMemo } from 'react'
import { useLocation, useNavigate, useRoutes } from 'react-router-dom'
import asyncRouterFun from './router/filterRouter'
import { sessionGetItem } from './utils/auth'
import { ConfigProvider } from 'antd'

import zhCN from 'antd/es/locale/zh_CN'
import en_US from 'antd/es/locale/en_US'
import 'styles/less/index.less'
import { useAppSelector } from './hooks/stroe'
import { i18n_config } from './store/modules/config'

function App() {
  const navigate = useNavigate()
  const location = useLocation()
  const token = sessionGetItem('token')
  const con_i18n = useAppSelector(i18n_config)
  // router
  const Router = useMemo(() => {
    const asyncRouter = asyncRouterFun()
    const result = () => useRoutes(asyncRouter)
    return result
  }, [token])
  // antd国际化
  const i18n = useMemo(() => {
    return con_i18n === 'zh' || !con_i18n ? zhCN : en_US
  }, [con_i18n])

  useEffect(() => {
    // 前置守卫
    if (token && location.pathname === '/') {
      navigate('/index')
      return
    }
    if (!token && location.pathname !== '/login') {
      navigate('/login')
      return
    }
    return () => {
      // 后置守卫
    }
  }, [token, location.pathname])

  return (
    <ConfigProvider locale={i18n}>
      <div className="App">
        <Router></Router>
      </div>
    </ConfigProvider>
  )
}

export default App
